package com.gjl.framework.web.service;

import com.alibaba.fastjson2.JSONObject;
import com.gjl.common.core.domain.entity.SysRole;
import com.gjl.common.core.domain.entity.SysUser;
import com.gjl.common.core.domain.model.LoginUser;
import com.gjl.common.core.domain.model.WxLoginBody;
import com.gjl.common.core.domain.model.response.WxLoginResponse;
import com.gjl.common.utils.http.HttpUtils;
import com.gjl.common.utils.ip.IpUtils;

import com.gjl.system.mapper.WxAuthUserMapper;
import com.gjl.system.service.ISysUserService;
import com.gjl.wechat.service.WechatAppletService;
import com.gjl.wechat.service.dto.applet.AppletDTO;
import com.gjl.wechat.service.dto.applet.AppletPhoneNumberRes;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName : WxLoginService
 * @Description : TODO
 * @Author : liuhui.jiao
 * @Date: 2025/10/28 22:04
 */
@Component
public class WxLoginService {


    // 配置日志操作
    private static final Logger logger = LoggerFactory.getLogger(WxLoginService.class);

    @Autowired
    WxAuthUserMapper wxAuthUserMapper;

    @Autowired
    TokenService tokenService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private UserDetailsServiceImpl impl;

    @Autowired
    private WechatAppletService wechatAppletService;

    @Value("${weChat.appid}")
    private String appId;

    @Value("${weChat.appsecret}")
    private String appSecret;

    @Value("${weChat.openIdUrl}")
    private String openIdUrl;

    /**
     * 登录方法
     * @param body 微信小程序信息和手机号
     * @return token
     */
    public WxLoginResponse login(WxLoginBody body){

        // 通过code获取openid
        String openid = getOpenid(body.getCode());
        // 判空
        if (openid == null){
            return null;
        }
        WxLoginResponse wxLoginResponse = new WxLoginResponse();
        wxLoginResponse.setOpenId(openid);

        // 通过openId查询数据库用户
        SysUser sysUser = userService.selectUserByOpenId(openid);
        // 如果用户不存在，说明是首次登录，返回openId  调用getPhoneByCode接口  将此openId放入header中
        if (sysUser == null) {
            return wxLoginResponse;
        }

        // 更新登录信息
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(new Date());
        userService.updateUser(sysUser);

        // 生成token并返回
        UserDetails userDetail = impl.createLoginUser(sysUser);
        LoginUser loginUser = new LoginUser();
        BeanUtils.copyProperties(userDetail, loginUser);
        loginUser.setOpenId(openid); // 假设LoginUser中有setOpenId方法
        String token = tokenService.createToken(loginUser);

        wxLoginResponse.setToken(token);
        wxLoginResponse.setUserId(sysUser.getUserId());
        wxLoginResponse.setAge(sysUser.getAge());
        wxLoginResponse.setPhonenumber(sysUser.getPhonenumber());
        wxLoginResponse.setProfession(sysUser.getProfession());
        wxLoginResponse.setIdCard(sysUser.getIdCard());
        wxLoginResponse.setDeptName(sysUser.getDept().getDeptName());
        wxLoginResponse.setKeepMedicine(0);

        List<SysRole> roles = sysUser.getRoles();
        if (CollectionUtils.isNotEmpty(roles)){
            List<WxLoginResponse.Role> roleList = roles.stream().map(
                    role -> new WxLoginResponse.Role(role.getRoleId(), role.getRoleName(),role.getRoleKey())
            ).collect(Collectors.toList());
            wxLoginResponse.setRoleNum(sysUser.getRoles().size());
            wxLoginResponse.setRole(roleList);
        }
        return wxLoginResponse;

    }


    /**
     * 检测手机号
     * @param phone 手机号
     * @return
     */
    public SysUser checkPhone(String phone){
        SysUser sysUser = userService.selectUserByPhone(phone);
        if (sysUser == null){
            return null;
        }
        return sysUser;
    }



    // 获取openid
    public String getOpenid(String code){
        // 获取openid ：GET https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
        // 请求参数应该是 name1=value1&name2=value2 的形式。

        String param = "appid=" + appId + "&secret=" + appSecret + "&js_code=" + code + "&grant_type=authorization_code";
        // {"session_key":"ReNqAU5cdvyhDccRY3SkFg==","openid":"oBWIX6ZfRE63r32e9rhW69DoN5wA"}
        String json = HttpUtils.sendGet(openIdUrl, param);
        // 将字符串形式的json转换为json对象
        JSONObject jsonObject = JSONObject.parseObject(json);
        // 取出openid
        Object openid = jsonObject.get("openid");
        if (openid == null){
            logger.error("WeChat Get openId error，code：{} json: {}",code, json);
            return null;
        }
        return (String) openid;
    }


    /**
     * 绑定手机号和openId
     * @param openId
     * @param code
     * @return
     */
    public SysUser relatedPhoneAndOpenId(String openId,String code){
        // 组装小程序信息
        AppletDTO build = AppletDTO.builder()
                .appid(appId)
                .appSecret(appSecret)
                .build();
        AppletPhoneNumberRes userphonenumber = wechatAppletService.getuserphonenumber(code, build);
        if (Objects.isNull(userphonenumber)){
            return null;
        }
        AppletPhoneNumberRes.PhoneInfo phoneInfo = userphonenumber.getPhoneInfo();
        String phoneNumber = phoneInfo.getPhoneNumber();
        SysUser sysUser = checkPhone(phoneNumber);
        if (sysUser == null){
            return null;
        }
        // 用户id不为空则将openId和手机号绑定
        sysUser.setOpenId(openId);
        userService.updateUser(sysUser);
        return sysUser;
    }


}
